package BarCode;

import java.util.HashMap;
import java.util.Map;

public class PostCode {

    static Map<String, String> numToBarCodeMap = new HashMap<String, String>();

    static {
        numToBarCodeMap.put("1",":::||");
        numToBarCodeMap.put("2","::|:|");
        numToBarCodeMap.put("3","::||:");
        numToBarCodeMap.put("4",":|::|");
        numToBarCodeMap.put("5",":|:|:");
        numToBarCodeMap.put("6",":||::");
        numToBarCodeMap.put("7","|:::|");
        numToBarCodeMap.put("8","|::|:");
        numToBarCodeMap.put("9","|:|::");
        numToBarCodeMap.put("0","||:::");
    }

    public static boolean isValidPostCode(String s) {
        if (s.contains("-") && 5 != s.indexOf("-")) {
            throw new RuntimeException("Error post-code, this post-code format is invalid.");
        }
        if (s.length() != 5 && s.length() != 9 && s.length() != 10) {
            throw new RuntimeException("Error post-code, this numbers of string is error.");
        }
        return true;
    }

    public static String toBarCode(String s) {
        if (s.contains("-")) {
            s = s.replace("-","");
        }
        char[] postCodeChars = s.toCharArray();
        int sum = 0;
        StringBuffer barCode = new StringBuffer("|");
        for (char postCodeChar : postCodeChars) {
            sum = sum + Integer.parseInt(String.valueOf(postCodeChar));
            barCode.append(numToBarCodeMap.get(String.valueOf(postCodeChar)));
        }
        int checkCode = 10 - sum % 10;
        if (checkCode == 10) {
            checkCode = 0;
        }
        barCode.append(numToBarCodeMap.get(String.valueOf(checkCode)));
        barCode.append("|");
        return barCode.toString();
    }
}
